import requestClass from "./requestClass";
import config from "@/config/index";
import { useUserStore } from "@/store/user";
// import { useUserStore } from '@/store/user'

const { requestPrefix, baseUrl, TOKEN_KEY } = config;

const ais = uni.getAccountInfoSync();
const env: string = ais.miniProgram.envVersion;
const Request = new requestClass();

// 请求拦截器

Request.interceptors.request((config: UniApp.RequestOptions) => {
  const userStore = useUserStore();

  if (userStore.token) {
    config.header["token"] = userStore.token;
  }

  const contentType: any = config.header.contentType;
  if (contentType) {
    config.header["content-type"] = contentType;
    delete config.header.contentType;
  } else if (config.method === "DELETE") {
    config.header["content-type"] = "application/x-www-form-urlencoded";
  } else {
    config.header["content-type"] = "application/json;charset=utf-8";
  }
  return config;
});

// 响应拦截器
Request.interceptors.response((response: any) => {
  const userStore = useUserStore();
  const { statusCode, data, errMsg } = response;
  const requestData = data as ApiResult<any>;
  console.log("response", response);
  if (statusCode !== 200) {
    uni.showToast({
      title: "网络错误！",
      icon: "none",
    });
    return Promise.reject(errMsg);
  }

  const { code, success, data: rData } = requestData;

  // token失效
  if (code === "401") {
    userStore.logout();
    return Promise.reject("登录信息过期,重新登录");
  }

  return requestData;
  // // 接口不行
  // return Promise.reject(requestData);
});

// 设置默认配置
Request.setConfig((config: any) => {
  config.baseURL = baseUrl[env] + requestPrefix[env];
  return config;
});

export default Request;
